import { ref, computed } from 'vue'

// 主题配置接口
export interface ThemeConfig {
  primaryColor: string
  secondaryColor: string
  fontSize: string
  fontFamily: string
  borderRadius: string
  spacing: string
}

// 预设主题
export const themePresets = {
  default: {
    primaryColor: '#3b82f6',
    secondaryColor: '#a855f7',
    fontSize: '14px',
    fontFamily: 'Inter, sans-serif',
    borderRadius: '6px',
    spacing: '16px'
  },
  dark: {
    primaryColor: '#60a5fa',
    secondaryColor: '#c084fc',
    fontSize: '14px',
    fontFamily: 'Inter, sans-serif',
    borderRadius: '6px',
    spacing: '16px'
  },
  compact: {
    primaryColor: '#3b82f6',
    secondaryColor: '#a855f7',
    fontSize: '12px',
    fontFamily: 'Inter, sans-serif',
    borderRadius: '4px',
    spacing: '12px'
  },
  large: {
    primaryColor: '#3b82f6',
    secondaryColor: '#a855f7',
    fontSize: '16px',
    fontFamily: 'Inter, sans-serif',
    borderRadius: '8px',
    spacing: '20px'
  }
}

// 当前主题状态
const currentTheme = ref<ThemeConfig>(themePresets.default)
const isDarkMode = ref(false)

// 主题组合式函数
export function useTheme() {
  // 设置主题
  const setTheme = (theme: ThemeConfig | keyof typeof themePresets) => {
    if (typeof theme === 'string') {
      currentTheme.value = { ...themePresets[theme] }
    } else {
      currentTheme.value = { ...theme }
    }
    applyThemeToDOM()
  }

  // 更新主题属性
  const updateTheme = (updates: Partial<ThemeConfig>) => {
    currentTheme.value = { ...currentTheme.value, ...updates }
    applyThemeToDOM()
  }

  // 切换暗色模式（SSR 安全）
  const toggleDarkMode = () => {
    isDarkMode.value = !isDarkMode.value
    if (typeof document !== 'undefined') {
      document.documentElement.classList.toggle('dark', isDarkMode.value)
    }
  }

  // 应用主题到DOM（SSR 安全）
  const applyThemeToDOM = () => {
    if (typeof document === 'undefined') return

    const root = document.documentElement
    const theme = currentTheme.value

    // 设置CSS变量
    root.style.setProperty('--theme-primary', theme.primaryColor)
    root.style.setProperty('--theme-secondary', theme.secondaryColor)
    root.style.setProperty('--font-size-default', theme.fontSize)
    root.style.setProperty('--radius-md', theme.borderRadius)
    root.style.setProperty('--spacing-md', theme.spacing)
  }

  // 获取主题颜色
  const getThemeColor = (color: 'primary' | 'secondary') => {
    return computed(() => {
      return color === 'primary' ? currentTheme.value.primaryColor : currentTheme.value.secondaryColor
    })
  }

  // 获取字体大小
  const getFontSize = () => {
    return computed(() => currentTheme.value.fontSize)
  }

  // 获取字体族
  const getFontFamily = () => {
    return computed(() => currentTheme.value.fontFamily)
  }

  // 获取圆角大小
  const getBorderRadius = () => {
    return computed(() => currentTheme.value.borderRadius)
  }

  // 获取间距大小
  const getSpacing = () => {
    return computed(() => currentTheme.value.spacing)
  }

  // 重置主题（SSR 安全）
  const resetTheme = () => {
    setTheme('default')
    isDarkMode.value = false
    if (typeof document !== 'undefined') {
      document.documentElement.classList.remove('dark')
    }
  }

  // 导出主题配置
  const exportTheme = () => {
    return JSON.stringify(currentTheme.value, null, 2)
  }

  // 导入主题配置
  const importTheme = (themeJson: string) => {
    try {
      const theme = JSON.parse(themeJson) as ThemeConfig
      setTheme(theme)
      return true
    } catch (error) {
      console.error('Invalid theme configuration:', error)
      return false
    }
  }

  // 初始化主题（SSR 安全）
  const initTheme = () => {
    // 从localStorage恢复主题设置
    const canUseStorage = typeof window !== 'undefined' && typeof localStorage !== 'undefined'
    const savedTheme = canUseStorage ? localStorage.getItem('officialblock-theme') : null
    const savedDarkMode = canUseStorage ? localStorage.getItem('officialblock-dark-mode') : null

    if (savedTheme) {
      try {
        const theme = JSON.parse(savedTheme) as ThemeConfig
        setTheme(theme)
      } catch (error) {
        console.error('Failed to restore theme:', error)
      }
    }

    if (savedDarkMode) {
      isDarkMode.value = savedDarkMode === 'true'
      if (typeof document !== 'undefined') {
        document.documentElement.classList.toggle('dark', isDarkMode.value)
      }
    }

    // 监听系统主题变化（仅客户端）
    if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
      const handleSystemThemeChange = (e: MediaQueryListEvent) => {
        if (!canUseStorage || !localStorage.getItem('officialblock-dark-mode')) {
          isDarkMode.value = e.matches
          if (typeof document !== 'undefined') {
            document.documentElement.classList.toggle('dark', isDarkMode.value)
          }
        }
      }
      mediaQuery.addEventListener('change', handleSystemThemeChange)
    }

    // 初始应用主题
    applyThemeToDOM()
  }

  // 保存主题设置（SSR 安全）
  const saveTheme = () => {
    if (typeof window !== 'undefined' && typeof localStorage !== 'undefined') {
      localStorage.setItem('officialblock-theme', JSON.stringify(currentTheme.value))
      localStorage.setItem('officialblock-dark-mode', isDarkMode.value.toString())
    }
  }

  return {
    // 状态
    currentTheme: computed(() => currentTheme.value),
    isDarkMode: computed(() => isDarkMode.value),
    themePresets,

    // 方法
    setTheme,
    updateTheme,
    toggleDarkMode,
    resetTheme,
    exportTheme,
    importTheme,
    initTheme,
    saveTheme,

    // 计算属性
    getThemeColor,
    getFontSize,
    getFontFamily,
    getBorderRadius,
    getSpacing
  }
}
